<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['mes:pro:protask:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['mes:pro:protask:edit']"
        >修改</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['mes:pro:protask:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['mes:pro:protask:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="protaskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务编号" align="center" prop="taskCode" fixed />
      <el-table-column label="任务名称" align="center" prop="taskName" fixed />
      <!-- <el-table-column label="工作站编号" align="center" width="150px" prop="workstationCode" :show-overflow-tooltip="true"/>
      <el-table-column label="工作站名称" align="center" width="150px" prop="workstationName" :show-overflow-tooltip="true"/>-->
      <!-- <el-table-column label="设备类型编码" align="center" prop="machineryCode" /> -->
      <el-table-column label="设备类型名称" align="center" prop="machineryName" />
      <el-table-column label="排产数量" align="center" prop="quantity" />
      <el-table-column label="已生产数量" align="center" width="100px" prop="quantityProduced" />
      <el-table-column label="开始生产时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生产时长(按班次（早8-晚8）)" align="center" prop="duration" />
      <el-table-column label="预计完成时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="显示颜色" align="center" prop="colorCode">
        <template slot-scope="scope">
          <el-color-picker v-model="scope.row.colorCode" disabled></el-color-picker>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="100px" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:pro:protask:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['mes:pro:protask:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改生产任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1080px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="machineryName">
              <el-input v-model="form.machineryName" disabled placeholder="请选择设备">
                <el-button slot="append" icon="el-icon-search" @click="handleMachinerySelect"></el-button>
              </el-input>
            </el-form-item>
            <MachinerySelect ref="machinerySelect" @onSelected="onMachinerySelect"></MachinerySelect>
            <!-- <el-form-item label="工作站" prop="workstationName">
              <el-input v-model="form.workstationName" placeholder="请选择工作站" >
                <el-button slot="append" icon="el-icon-search" @click="handleWorkstationSelect"></el-button>
              </el-input>
            </el-form-item>
            <WorkstationSelect ref="wsSelect" :processId="processId"  @onSelected="onWorkstationSelected"> </WorkstationSelect>-->
          </el-col>
          <el-col :span="5">
            <el-form-item label="甘特图显示颜色" prop="colorCode">
              <el-color-picker v-model="form.colorCode"></el-color-picker>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-input v-model="form.colorCode" maxlength="7" placeholder="请输入颜色编码在左侧选择颜色" />
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="排产数量" prop="quantity">
              <el-input-number :min="1" v-model="form.quantity" placeholder="请输入排产数量" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker clearable v-model="form.startTime" :picker-options="pickerOptions"
                @change="calculateEndTime" type="datetime" value-format="yyyy-MM-dd HH"
                placeholder="请选择开始生产时间"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生产时长" prop="duration">
              <el-input v-model="form.duration" @change="calculateEndTime" disabled :formatter="zeroFormatter"
                @blur="onBlur()" placeholder="请输入生产时长" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="完成时间" prop="endTime">
              <el-date-picker clearable disabled v-model="form.endTime" type="datetime"
                value-format="yyyy-MM-dd HH"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-form-item label="报表类型" prop="formType">
          <el-select v-model="form.formType" placeholder="请选择报表类型">
            <el-option v-for="dict in dict.type.mes_form_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listProtask,
  getProtask,
  delProtask,
  addProtask,
  updateProtask,
} from "@/api/mes/pro/protask";
import WorkstationSelect from "@/components/workstationSelect/simpletableSingle.vue";
import MachinerySelect from "@/components/machinerySelect/single.vue";
export default {
  name: "Protask",
  components: { WorkstationSelect, MachinerySelect },
  dicts: ["mes_form_type"],
  data() {
    return {
      value1: null,
      // 遮罩层
      loading: true,
      // 工艺总排产数量
      allProtaskCount:0,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产任务表格数据
      protaskList: [],
      // 弹出层标题
      title: "",
      // 机器产能
      capacity: null,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskCode: null,
        taskName: null,
        workorderId: this.workorderId,
        workorderCode: null,
        workorderName: null,
        workstationId: null,
        workstationCode: null,
        workstationName: null,
        processId: this.processId,
        processCode: null,
        processName: null,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        quantity: null,
        quantityProduced: null,
        quantityChanged: null,
        clientId: null,
        clientCode: null,
        clientName: null,
        clientNick: null,
        startTime: null,
        duration: null,
        endTime: null,
        colorCode: null,
        requestDate: null,
      },
      // 表单参数
      form: {},
      pickerOptions: {
        disabledDate: (time) => {
          if (this.workTime) {
            const forbiddenDate = new Date(this.workTime.requestDate);
            return time.getTime() > forbiddenDate.getTime();
          }
        },
        selectableRange: ["08:00:00-08:00:00", "20:00:00-20:00:00"],
      },
      // 表单校验
      rules: {
        machineryName: [
          { required: true, message: "设备不能为空", trigger: "blur" },
        ],
        workstationId: [
          { required: true, message: "工作站不能为空", trigger: "blur" },
        ],
        quantity: [
          { required: true, message: "排产数量不能为空", trigger: "blur" },
        ],
        startTime: [
          { required: true, message: "请选择开始生产日期", trigger: "blur" },
        ],
        // duration: [
        //   { required: true, message: "请输入估算的生产用时", trigger: "blur" },
        // ],
        // formType: [
        //   { required: true, message: "请选择报表类型", trigger: "blur" },
        // ],
      },
    };
  },
  props: {
    workorderId: null,
    colorCode: null,
    processId: null,
    optType: null,
    quantity: null,
    workTime: null,
  },
  watch: {
    "form.quantity"(newVal, oldVal) {
      if (this.form.quantity && this.capacity) {
        this.form.duration = Math.ceil(
          parseInt(this.form.quantity) / parseInt(this.capacity)
        );
      }
    },
    "form.duration"(newVal, oldVal) {
      this.calculateEndTime();
    },
  },
  created() {
    this.getList();
    this.getAllList();
    this.$nextTick(() => {
      if (this.$refs.table) {
        this.$refs.table.doLayout();

      }
    });
  },
  methods: {
    /** 查询生产任务列表 */
    getList() {
      this.loading = true;
      listProtask(this.queryParams).then((response) => {
        this.protaskList = response.rows;
        console.log(response.rows, "response.rows");
        this.total = response.total;
        this.loading = false;
      });
    },
    getAllList(){
      let obj = {
        pageNum:1,
        pageSize:9999,
        workorderId:this.workorderId,
      }
      listProtask(obj).then((response) => {       
        response.rows.map((item)=>{
          this.allProtaskCount += item.quantity;
        });
        console.log( this.allProtaskCount,this.quantity, "response.rowsrowsrows");
      });
    },
    //计算结束时间
    onBlur() {
      if (this.form.duration === "") {
        this.form.duration = 0;
        return this.form.duration;
      }
    },
    zeroFormatter(value) {
      if (value === "0" || value === "") {
        return value;
      }
      return parseInt(value);
    },
    // 获取当前日期时间格式
    getCurrentDateTime() {
      let now, year, month, day, hours = ''
      // 当天
      now = new Date();
      year = now.getFullYear();
      console.log(now, 'now22222')
      month = (now.getMonth() + 1).toString().padStart(2, '0');
      day = now.getDate().toString().padStart(2, '0');
      hours = now.getHours().toString().padStart(2, '0');
      return `${year}-${month}-${day} ${hours}`;
    },
    calculateEndTime() {
      // console.log(this.form.startTime, this.form.duration, '开始时间打印111')
      if (this.form.startTime) {
        if (this.form.duration) {
          this.form.duration = parseFloat(this.form.duration);
        }
        // 当开始时间为默认点击日期组件确认按钮时的操作
        if (this.form.startTime == this.getCurrentDateTime()) {
          this.form.startTime = ''
        } else {
          this.setTimesFunc(this.form.startTime)
        }
      } else {
        if (this.form.startTime == this.getCurrentDateTime()) {
          this.form.startTime = ''
         
        }
      }
      console.log(this.form.startTime, this.form.duration, this.form.endTime, 'this.form.duration22222')
    },
    // 设置时间的函数
    setTimesFunc(startTime) {
      // console.log(startTime, 'startTimestartTime')
      let parts = startTime.split(" ");
      // console.log(parts, 'parts')
      let startDate = new Date(parts[0]);
      startDate =
        startDate.getFullYear() +
        "-" +
        (startDate.getMonth() + 1) +
        "-" +
        startDate.getDate() +
        " " +
        parts[1].split(":")[0] +
        ":" +
        "00" +
        ":" +
        "00";
      this.form.startTime = startDate;
      startDate = Date.parse(new Date(startDate)) / 1000;
      startDate += 3600 * 12 * this.form.duration; //这里以12小时为一个单位
      let endDate = new Date(parseInt(startDate) * 1000);

      this.form.endTime =
        endDate.getFullYear() +
        "-" +
        (endDate.getMonth() + 1) +
        "-" +
        endDate.getDate() +
        " " +
        endDate.getHours() +
        ":" +
        endDate.getMinutes() +
        ":" +
        endDate.getSeconds();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        taskId: null,
        taskCode: null,
        taskName: null,
        workorderId: this.workorderId,
        workorderCode: null,
        workorderName: null,
        workstationId: null,
        workstationCode: null,
        workstationName: null,
        processId: this.processId,
        processCode: null,
        processName: null,
        itemId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        quantity: this.quantity,
        quantityProduced: null,
        quantityChanged: null,
        clientId: null,
        clientCode: null,
        clientName: null,
        clientNick: null,
        startTime: null,
        duration: null,
        endTime: null,
        colorCode: this.colorCode,
        requestDate: null,
        remark: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        machineryId: null,
        machineryCode: null,
        machineryName: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.taskId);
      console.log(this.ids, ' this.ids')
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加生产任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const taskId = row.taskId || this.ids;
      getProtask(taskId).then((response) => {
        this.form = response.data;
        // this.form.startTime = new Date(response.data.startTime);
        // this.form.endTime = new Date(response.data.endTime);
        this.open = true;
        this.title = "修改生产任务";
      });
    },
    /** 提交按钮 */
    submitForm() {
      let count = this.form.quantity + this.allProtaskCount
      console.log(count, 'count')
      if(count > this.quantity){
        this.$confirm('当前总排产数量大于工单数量是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.submitFn()
        }).catch(() => {});
      }else{
        this.submitFn()
      }
    },
    submitFn(){
      this.$refs["form"].validate((valid) => {
        console.log(this.form, valid, 'sdadas');

        if (valid) {

          if (this.form.taskId != null) {
            updateProtask(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // console.log(this.form);
            addProtask(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const taskIds = row.taskId || this.ids;
      this.$modal
        .confirm('是否确认删除生产任务编号为"' + taskIds + '"的数据项？')
        .then(function () {
          return delProtask(taskIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "mes/pro/protask/export",
        {
          ...this.queryParams,
        },
        `protask_${new Date().getTime()}.xlsx`
      );
    },
    // 弹出工作站对话框
    handleWorkstationSelect() {
      this.$refs.wsSelect.showFlag = true;
    },
    // 工作站回调函数
    onWorkstationSelected(row) {

      if (row != undefined && row != null) {
        this.form.workstationId = row.workstationId;
        this.form.workstationCode = row.workstationCode;
        this.form.workstationName = row.workstationName;
      }
    },
    // 选择设备
    handleMachinerySelect() {
      this.$refs.machinerySelect.showFlag = true;
    },
    // 选中设备回调
    onMachinerySelect(row) {
      if (row) {

        this.form.machineryId = row.machineryId;
        this.form.machineryName = row.machineryName;
        this.form.machineryCode = row.machineryCode;
        this.capacity = row.capacity;
        this.form.duration = Math.ceil(
          parseInt(this.form.quantity) / parseInt(row.capacity)
        );
        console.log(this.form, row, "row111");
      }
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep.el-table {
  transform: scale(1);
}
</style>